package com.ys.util;

import com.ys.pojo.Administrators;
import com.ys.service.AdministratorsService;
import com.ys.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Resource
    private AdministratorsService administratorsService;
    @Resource
    private MenuService menuService;

    @Resource
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Administrators ad = (Administrators) principalCollection.getPrimaryPrincipal();
        List<String> list = menuService.finByGrname(ad.getAccount());
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.addStringPermissions(list);
        System.out.println("------------------------------------------");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userCode = (String) authenticationToken.getPrincipal();
        Administrators administrators = administratorsService.login(userCode);
        if(administrators==null){
            return null;
        }
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("objs",administrators);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(administrators,administrators.getPassword(), ByteSource.Util.bytes(administrators.getPwdshiro()),super.getName());
        return info;
    }
}
